package com.woniuxy.kaer.service.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.kaer.commons.util.Data;
import com.woniuxy.kaer.service.entity.ServiceOrder;
import com.woniuxy.kaer.service.entity.ServiceOrderLog;
import com.woniuxy.kaer.service.entity.ServiceProcesses;
import com.woniuxy.kaer.service.mapper.ServiceOrderLogMapper;
import com.woniuxy.kaer.service.mapper.ServiceOrderMapper;
import com.woniuxy.kaer.service.mapper.ServiceProcessesMapper;
import com.woniuxy.kaer.service.param.UpdateServiceProcessesParam;
import com.woniuxy.kaer.service.service.ServiceProcessesService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年02月17日
 */
@Service
public class ServiceProcessesServiceImpl extends ServiceImpl<ServiceProcessesMapper, ServiceProcesses> implements ServiceProcessesService {

    @Resource
    private ServiceOrderMapper serviceOrderMapper;
    @Resource
    private ServiceProcessesMapper serviceProcessesMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ServiceOrderLogMapper serviceOrderLogMapper;

    @Override
    public void updateServiceProcesses(UpdateServiceProcessesParam param) throws Exception {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(param.getServiceOrderId());
        if(null==serviceOrder){
            throw new RuntimeException("订单不存在");
        }

        ServiceProcesses serviceProcesses = serviceProcessesMapper.selectById(param.getServiceProcessesId());
        if (null==serviceProcesses){
            throw new RuntimeException("服务流程不存在");
        }
        if(Data.SERVICE_PROCESSES_STATE_NOT_COMPLETE!=serviceProcesses.getState()){
            throw new RuntimeException("服务流程状态异常");
        }
        serviceProcesses.setState(Data.SERVICE_PROCESSES_STATE_COMPLETE);
        serviceProcessesMapper.updateById(serviceProcesses);
        if(serviceProcesses.getSerialNumber()==1){
            serviceOrder.setServiceOrderState(Data.SERVICE_ORDER_STATE_PROCESSING);
            serviceOrderMapper.updateById(serviceOrder);
        }
        //对最后一个进行更改时，，订单状态改变为完成
        QueryWrapper<ServiceProcesses> serviceProcessesQueryWrapper = new QueryWrapper<>();
        serviceProcessesQueryWrapper.eq("service_order_id",param.getServiceOrderId());
        List<ServiceProcesses> serviceProcesses1 = serviceProcessesMapper.selectList(serviceProcessesQueryWrapper);
        if(serviceProcesses1.size()==serviceProcesses.getSerialNumber()){
            //rabbitTemplate.convertAndSend("","waiting_check_finish_queue",param.getServiceOrderId());
            new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String xxlLoginAPI="http://192.168.50.8:9000/xxl-job-admin/login";
                            String xxlAddJobAPI="http://192.168.50.8:9000/xxl-job-admin/jobinfo/add";
//                            String xxlLoginAPI="http://localhost:8888/xxl-job-admin/login";
//                            String xxlAddJobAPI="http://localhost:8888/xxl-job-admin/jobinfo/add";
                            HashMap<String, Object> loginParam = new HashMap<String,Object>();
                            loginParam.put("userName", "admin");
                            loginParam.put("password", "123456");
                            HttpResponse httpResponse = HttpRequest.post(xxlLoginAPI).form(loginParam).execute();
                            if(httpResponse.getStatus()==200) {
                                System.out.println("登录成功");
                                Map<String, Object> addTaskParam = new HashMap<String,Object>();
                                //addTaskParam.put("jobGroup", 5);
                                addTaskParam.put("jobGroup", 5);
                                LocalDateTime now = LocalDateTime.now();
                                LocalDateTime executeTime = now.plusHours(3);
                                int year = executeTime.get(ChronoField.YEAR);
                                int month = executeTime.get(ChronoField.MONTH_OF_YEAR);
                                int day = executeTime.get(ChronoField.DAY_OF_MONTH);
                                int hour=executeTime.get(ChronoField.HOUR_OF_DAY);
                                int minute=executeTime.get(ChronoField.MINUTE_OF_HOUR);
                                int second=executeTime.get(ChronoField.SECOND_OF_MINUTE);
                                StringBuilder cron = new StringBuilder();
                                cron.append(second);
                                cron.append(" "+minute);
                                cron.append(" "+hour);
                                cron.append(" "+day);
                                cron.append(" "+month);
                                cron.append(" ?");
                                cron.append(" "+year);
                                System.out.println(cron.toString());
                                addTaskParam.put("scheduleConf", cron.toString());
                                addTaskParam.put("jobDesc", "系统确认订单任务");
                                addTaskParam.put("author", "系统");
                                addTaskParam.put("executorHandler", "confirmsOrderHandler");
                                addTaskParam.put("executorParam",serviceOrder.getServiceOrderId());//测试的拼团编号
                                addTaskParam.put("scheduleType", "CRON");
                                addTaskParam.put("executorRouteStrategy", "FIRST");
                                addTaskParam.put("executorBlockStrategy", "SERIAL_EXECUTION");
                                addTaskParam.put("glueType", "BEAN");
                                addTaskParam.put("misfireStrategy","DO_NOTHING");
                                addTaskParam.put("executorTimeout", "0");
                                addTaskParam.put("executorFailRetryCount","0");
                                addTaskParam.put("triggerStatus", 1);
                                HttpResponse response = HttpRequest.post(xxlAddJobAPI).form(addTaskParam).execute();
                                //System.out.println(response.body());
                                //从body中取出content content代表任务ID
                                //使用redis保存拼团编号-任务ID键值对
                                if(response.getStatus()!=200) {
                                    throw new Exception("预约时间超时任务失败");
                                }
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
        }
        //日志服务记录（记录进度日志）
        ServiceOrderLog serviceOrderLog = new ServiceOrderLog();
        serviceOrderLog.setServiceOrderId(param.getServiceOrderId());
        serviceOrderLog.setOperator(serviceProcesses.getCurrentOperator());
        serviceOrderLog.setOptionType(serviceProcesses.getProcessesName());
        serviceOrderLog.setOptionTime(LocalDateTime.now());
        serviceOrderLogMapper.insert(serviceOrderLog);
    }

    @Override
    public List<ServiceProcesses> getServiceProcessesByServiceOrderId(String serviceOrderId) throws Exception {
        QueryWrapper<ServiceProcesses> serviceProcessesQueryWrapper = new QueryWrapper<>();
        serviceProcessesQueryWrapper.eq("service_order_id",serviceOrderId);
        List<ServiceProcesses> serviceProcesses = serviceProcessesMapper.selectList(serviceProcessesQueryWrapper);
        return serviceProcesses;
    }
}
